import tkinter as tk
import Main
import requests
#from icon import img
import base64
import os
import tkinter.messagebox
import sys
import urllib.request
import re
import tkinter.font as tkFont


def clear():
    list1.delete(0, tk.END)

def check_initialize():
    v1.set(1)
    v2.set(1)
    v3.set(1)
    v4.set(1)
    v5.set(1)

if __name__ == "__main__":

    #创建新窗口
    root = tk.Tk()

    # 设置窗口大小
    #root.geometry('400x300')

    # 设置标题
    root.title('一键下财报【版权所有】')

    tk.Grid.rowconfigure(root, 0, weight=2)
    tk.Grid.columnconfigure(root, 0, weight=2)

    #创建标题字体统一格式
    ft_title = tkFont.Font(family='微软雅黑', size=12, weight=tkFont.BOLD)

    #创建小字
    ft_tiny = tkFont.Font(family='微软雅黑', size=8)

    #创建正文字体统一格式
    ft_content = tkFont.Font(family='Times', size=8, weight=tkFont.NORMAL)

    # 创建引导标签对象并添加到顶层窗口
    label1 = tk.Label(root, text='请输入查询上市公司6位证券代码', fg='red', font=ft_title, padx=10, pady=10, borderwidth=5,
                   justify='center')
    label1.grid(sticky="W", row = 0, column=0)

    #创建输入框对象并添加到顶层窗口
    input1 = tk.Entry(root)
    input1.grid(sticky="E", row=0, column=1, padx=20)
    input1.focus()

    # 创建财报列表Listbox
    list1 = tk.Listbox(root, selectmode=tk.MULTIPLE)
    list1.grid_forget()

    # 创建滚动条Scrollbar
    sb = tk.Scrollbar(root)
    sb.grid_forget()

    #创建Frame
    frame1 = tk.Frame(root, bd=1, relief='groove')
    frame2 = tk.Frame(root, bd=1, relief='groove')
    frame1.grid_forget()
    frame2.grid_forget()

    # 创建筛选按钮CheckButton(多选) #默认选中
    v1 = tk.IntVar()
    v2 = tk.IntVar()
    v3 = tk.IntVar()
    v4 = tk.IntVar()
    v5 = tk.IntVar()
    check_initialize()

    c1 = tk.Checkbutton(frame1, text='年度报告', variable=v1)
    c2 = tk.Checkbutton(frame1, text='半年度报告', variable=v2)
    c3 = tk.Checkbutton(frame1, text='Q1报告', variable=v3)
    c4 = tk.Checkbutton(frame1, text='Q3报告', variable=v4)
    c5 = tk.Checkbutton(frame1, text='其他', variable=v5)
    c1.pack_forget()
    c2.pack_forget()
    c3.pack_forget()
    c4.pack_forget()
    c5.pack_forget()

    temp_titles = []
    temp_art_codes = []
    temp_types = []
    temp_type_codes = []

    def show():
        clear()
        check_initialize()
        InputCode = input1.get()
        if len(InputCode) == 6 and InputCode.isdigit():
            print(len(InputCode))
            print(InputCode)
            list1.grid(sticky="S", row = 1, column=0, ipadx=40)
            sb.grid(row=1, column=0, sticky='nse')
            list1.configure(yscrollcommand=sb.set)
            sb.configure(command=list1.yview)
            frame1.grid(row=1, column=1, sticky='N')
            frame2.grid(row=1, column=1, sticky='S')
            c1.pack()
            c2.pack()
            c3.pack()
            c4.pack()
            c5.pack()

            # 向List1导入数据
            company_id = InputCode
            art_codes, titles, types, type_codes = Main.statement_list(company_id)
            temp_art_codes = art_codes.copy()
            temp_titles = titles.copy()
            temp_types = types.copy()
            temp_type_codes = type_codes.copy()
            print(art_codes)
            print(types)
            print(type_codes)
            for title in titles:
                list1.insert(0, title)

            def screen():
                clear()
                indices = []
                #清空临时统计列表
                temp_titles.clear()
                temp_art_codes.clear()
                temp_types.clear()
                temp_type_codes.clear

                print(v1.get(), v2.get(), v3.get(), v4.get(), v5.get())
                if v1.get() == 1: #年度报告 001001001001002
                    for index, type_code in enumerate(type_codes):
                        if type_code == "001001001001001":
                            indices.append(index)
                if v2.get() == 1: #半年度报告 001001001002002
                    for index, type_code in enumerate(type_codes):
                        if type_code == "001001001002001":
                            indices.append(index)
                if v3.get() == 1: #Q1报告 001001001003001
                    for index, type_code in enumerate(type_codes):
                        if type_code == "001001001003001":
                            indices.append(index)
                if v4.get() == 1: #Q3报告 001001001004001
                    for index, type_code in enumerate(type_codes):
                        if type_code == "001001001004001":
                            indices.append(index)
                if v5.get() == 1: #其他所有不为以上四种的情况
                    for index, type_code in enumerate(type_codes):
                        if type_code not in ["001001001001001", "001001001002001", "001001001003001", "001001001004001"]:
                            indices.append(index)
                print(indices)
                #创建临时统计列表
                for index in indices:
                    temp_titles.append(titles[index])
                    temp_types.append(types[index])
                    temp_art_codes.append(art_codes[index])
                    temp_type_codes.append(type_codes[index])
                #在ListBox里创建新列表
                for temp_title in temp_titles:
                    list1.insert(0, temp_title)
                print(titles)

            def download():
                selections = []
                print(temp_art_codes)
                print(temp_titles)
                print(list1.curselection())
                Curselections = list(list1.curselection())
                print(Curselections)
                for Curselection in Curselections:
                    selections.append(-1-int(Curselection))
                print(selections)

                for selection in selections:
                    print(temp_art_codes[selection])
                    url = "https://pdf.dfcfw.com/pdf/H2_" + str(temp_art_codes[selection]) + "_1.pdf"
                    r = requests.get(url)
                    with open(temp_titles[selection].replace(":", "") + ".pdf", "wb") as code:
                        code.write(r.content)
                        #print("done")

                if len(selections) > 0:
                    tk.messagebox.showinfo(title="提醒", message="下载完成！")
                else:
                    tk.messagebox.showinfo(title="提醒", message="至少选择一个报告文件完成下载！")
                #clear()

            #创建筛选和下载按钮Button

            tk.Button(frame2, text="筛选", width=10, bg="grey", command = screen).grid(row=0, column=0)
            tk.Button(frame2, text="下载", width=10, bg="white", command = download).grid(row=0, column=1)

            #command = screen
            #command = downloader

            """
            c1.grid(row=1, column=1, sticky = 'N')
            c2.grid(row=2, column=1, sticky = 'N')
            c3.grid(row=3, column=1, sticky = 'N')
            c4.grid(row=4, column=1, sticky = 'N')
            """
        else:
            tk.messagebox.showinfo(title="警告", message="证券代码有误！请检查代码长度是否6位数且为纯数字！目前仅支持A股公司查询")


    #def screen():

    # 创建作者信息
    label2 = tk.Label(root, text='提修改意见/找bug联系作者VX:huyuepeng0328', font=ft_tiny, padx=10, pady=10, borderwidth=5,
                      justify='center')
    label2.grid( row=4, column=0, rowspan=2)

    tk.Button(root, text="查询公司", width=10, command=show, bd=3).grid(row=3, column=0, sticky="w", padx=10, pady=5)
    tk.Button(root, text="退出", width=10, command=root.quit).grid(row=3, column=1, sticky="e", padx=10, pady=5)

    root.mainloop()

#test v3.0


